package com.qianguo.buyer;

import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.Product;
import com.eva.androidlibrary.api.entity.ProductList;
import com.eva.androidlibrary.api.entity.ShopInfo;
import com.eva.androidlibrary.image.ImageLoader;
import com.eva.androidlibrary.widget.SwipeRefreshRecyclerView;
import com.qianguo.buyer.base.BaseTitleActivity;
import com.qianguo.buyer.constant.BuyerKeys;
import com.qianguo.buyer.entity.AddShopCar;
import com.qianguo.buyer.widget.dropdownmenu.BaseMenuFilterItem;
import com.qianguo.buyer.widget.dropdownmenu.DropDownFilterListView;
import com.qianguo.buyer.widget.dropdownmenu.DropDownMenu;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 水果列表
 *
 * @author guxun
 * @date 2016-06-27 19:43
 */
@EActivity(R.layout.activity_shop_fruit_list_main)
public class ShopFruitListActivity extends BaseTitleActivity {
    private String headers[] = {"分类", "按销量", "按价格"};
    List<BaseMenuFilterItem> mFilterListValues, mFilterListSaleValues, mFilterListPriceValues;
    private List<View> popupViews = new ArrayList<>();
    @ViewById(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    private SimpleRecyclerCardAdapter mSimpleRecyclerAdapter;
    private SwipeRefreshRecyclerView mFruitListView;
    private RelativeLayout mRlShopCar;
    private TextView mTvShopCarPrice;
    private LinearLayout mLlShopCar;
    private int mCurrentPage = 1, mPerPage = 20, mCategoryId, mOrderTypeID;
    private static int INVALID_CODE = 0;
    private static int STAGGERED_NUM = 2;//网格列表数量2列
    private List<Product> mFruitListData = new ArrayList<>();
    private List<Integer> mSelectFruit = new ArrayList<>();

    @Extra(BuyerKeys.EXTRA_KEY_SHOP_INFO)
    ShopInfo mShop;

    public static void jumpToShop(Context context, ShopInfo shop) {
        Intent intent = new Intent();
        intent.setClass(context, ShopFruitListActivity_.class);
        intent.putExtra(BuyerKeys.EXTRA_KEY_SHOP_INFO, shop);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return "";
    }

    @Override
    protected void initializeUI() {
        mCategoryId = mOrderTypeID = INVALID_CODE;
        setToolBarTitle(mShop.getName());
        initFilterView();
        initFruitListView();
        getShopFruitList();
    }

    /**
     * 获取水果列表
     */
    @Background
    void getShopFruitList() {
        mApp.getApi().getShopFruitList(mCurrentPage, mPerPage, mShop == null ? "2" : mShop.getId(), mCategoryId, mOrderTypeID, new HttpRequestCallback<ProductList>() {
            @Override
            public void onSuccess(int code, String msg, ProductList data) {
                if (data.getList().size() > 0) {
                    mFruitListData.addAll(data.getList());
                }
                refreshUI();
            }


            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    /**
     * 初始化水果列表UI
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void initFruitListView() {
        mSimpleRecyclerAdapter = new SimpleRecyclerCardAdapter(this);
        mFruitListView.setAdapter(mSimpleRecyclerAdapter);
        mFruitListView.setSwipeRefreshListener(new SwipeRefreshRecyclerView.SwipeRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                mFruitListData.clear();
                getShopFruitList();
            }

            @Override
            public void onLoadMore() {
                mCurrentPage++;
                getShopFruitList();
            }
        });
        //设置网格布局管理器
        mFruitListView.setRecyclerLayoutManager(new StaggeredGridLayoutManager(STAGGERED_NUM, StaggeredGridLayoutManager.VERTICAL));
        mSimpleRecyclerAdapter.setOnItemActionListener(new OnItemActionListener() {

            @Override
            public void onItemAddClickListener(View v, int pos) {
                if (mRlShopCar.getVisibility() != View.VISIBLE) {
                    mRlShopCar.setVisibility(View.VISIBLE);
                }

                updateShopCar(pos);
            }

            @Override
            public void onItemClickListener(View v, int pos) {
                if (mRlShopCar.getVisibility() != View.VISIBLE) {
                    mRlShopCar.setVisibility(View.VISIBLE);
                }
                if (!mSelectFruit.contains(pos)) {
                    updateShopCar(pos);
                }
            }
        });

    }

    private void updatePriceInfo() {
        int priceAll = 0;
        for (Integer entry : mSelectFruit) {
            priceAll += mFruitListData.get(entry).getPrice();
        }
        mTvShopCarPrice.setText(mSelectFruit.size() + "份,约" + priceAll + "元");
    }

    private void updateShopCar(int pos){
        mSelectFruit.add(pos);
        Product product = mFruitListData.get(pos);
        addShopFruitCar(product.getId(), 0, 0, 1);
        updatePriceInfo();
    }

    /**
     * 初始化筛选器UI
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void initFilterView() {
        createRegionData();
        DropDownFilterListView filterListView = (DropDownFilterListView) getLayoutInflater().inflate(R.layout.item_fruit_list_filter_1, null);
        DropDownFilterListView filterSaleListView = (DropDownFilterListView) getLayoutInflater().inflate(R.layout.item_fruit_list_filter_1, null);
        DropDownFilterListView filterPriceListView = (DropDownFilterListView) getLayoutInflater().inflate(R.layout.item_fruit_list_filter_1, null);

        filterListView.showSingleListFilter(mFilterListValues, new DropDownFilterListView.OnConditionSelectedListener() {

            @Override
            public void onFilterSelected(BaseMenuFilterItem item, int a) {
                mCategoryId = item.getiCodeID();
                mDropDownMenu.setTabText(item.getsName());
                mDropDownMenu.closeMenu();
                getShopFruitList();
            }
        });
        filterSaleListView.showSingleListFilter(mFilterListSaleValues, new DropDownFilterListView.OnConditionSelectedListener() {

            @Override
            public void onFilterSelected(BaseMenuFilterItem item, int a) {
                mOrderTypeID = item.getiCodeID();
                mDropDownMenu.setTabText(item.getsName());
                mDropDownMenu.closeMenu();
                getShopFruitList();
            }
        });
        filterPriceListView.showSingleListFilter(mFilterListPriceValues, new DropDownFilterListView.OnConditionSelectedListener() {

            @Override
            public void onFilterSelected(BaseMenuFilterItem item, int a) {
                mOrderTypeID = item.getiCodeID();
                mDropDownMenu.setTabText(item.getsName());
                Toast.makeText(ShopFruitListActivity.this, "content is " + item.getsName() + "\n position is " + a, Toast.LENGTH_SHORT).show();
                mDropDownMenu.closeMenu();
                getShopFruitList();
            }
        });

        popupViews.add(filterListView);
        popupViews.add(filterSaleListView);
        popupViews.add(filterPriceListView);
        View content = getLayoutInflater().inflate(R.layout.activity_shop_fruit_list, null);
        mFruitListView = (SwipeRefreshRecyclerView) content.findViewById(R.id.rv_fruit_list);
        mRlShopCar = (RelativeLayout) content.findViewById(R.id.rl_shp_car);
        mLlShopCar = (LinearLayout) content.findViewById(R.id.ll_shp_car);
        mTvShopCarPrice = (TextView) content.findViewById(R.id.tv_fruit_price);
        mLlShopCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShopCarDetailActivity.jumpToShopCarDetail(ShopFruitListActivity.this, mShop != null ? mShop.getId() : "");
            }
        });
        if (popupViews.size() == headers.length) {
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, content);
        }
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void refreshUI() {
        mFruitListView.onCompleted();
        mFruitListView.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        //退出activity前关闭菜单
        if (mDropDownMenu.isShowing()) {
            mDropDownMenu.closeMenu();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 装载筛选器控件数据
     */
    private void createRegionData() {
        java.util.Random random = new java.util.Random();
        int totalLeft = random.nextInt(5) + 3;
        mFilterListValues = new ArrayList<>();
        mFilterListSaleValues = new ArrayList<>();
        mFilterListPriceValues = new ArrayList<>();
        for (int j = 0; j < totalLeft; j++) {
            BaseMenuFilterItem item1 = new BaseMenuFilterItem();
            item1.setiCodeID(j);
            item1.setsName("区域" + j);
            mFilterListValues.add(item1);
        }

        for (int j = 0; j < random.nextInt(2) + 3; j++) {
            BaseMenuFilterItem itemBase = new BaseMenuFilterItem();
            itemBase.setiCodeID(j);
            itemBase.setsName("销量" + j);
            mFilterListSaleValues.add(itemBase);
        }
        for (int j = 0; j < random.nextInt(1) + 3; j++) {
            BaseMenuFilterItem itemBase = new BaseMenuFilterItem();
            itemBase.setiCodeID(j);
            itemBase.setsName("价格" + j);
            mFilterListPriceValues.add(itemBase);
        }
    }

    public class SimpleRecyclerCardAdapter extends RecyclerView.Adapter<SimpleCardViewHolder> {

        private Context mCtx;
        private LayoutInflater mInflater;
        private OnItemActionListener mOnItemActionListener;

        public SimpleRecyclerCardAdapter(Context mCtx) {
            super();
            this.mCtx = mCtx;
            mInflater = LayoutInflater.from(mCtx);
        }

        @Override
        public int getItemCount() {
            return mFruitListData.size();
        }

        @Override
        public void onBindViewHolder(final SimpleCardViewHolder viewHolder, int i) {
            viewHolder.tvTitle.setText(mFruitListData.get(i).getName());
            viewHolder.tvPrice.setText("¥" + mFruitListData.get(i).getPrice() + mFruitListData.get(i).getUnit());
            ImageLoader.getInstance(mCtx).loadImage(mCtx, viewHolder.ivPic, mFruitListData.get(i).getCover(), R.mipmap.default_avatar);
            if (mOnItemActionListener != null) {
                viewHolder.ivPic.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mOnItemActionListener.onItemClickListener(v, viewHolder.getPosition());
                    }
                });
                viewHolder.tvAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnItemActionListener.onItemAddClickListener(v, viewHolder.getPosition());
                    }
                });
            }
        }

        @Override
        public SimpleCardViewHolder onCreateViewHolder(ViewGroup viewgroup, int i) {

            View v = mInflater.inflate(R.layout.item_fruist_card_list, viewgroup, false);
            SimpleCardViewHolder simpleViewHolder = new SimpleCardViewHolder(v);
            simpleViewHolder.setIsRecyclable(true);

            return simpleViewHolder;
        }


        public void setOnItemActionListener(OnItemActionListener onItemActionListener) {
            this.mOnItemActionListener = onItemActionListener;
        }
    }

    static class SimpleCardViewHolder extends RecyclerView.ViewHolder {
        public TextView tvTitle;
        public TextView tvPrice;
        public TextView tvAdd;
        public ImageView ivPic;

        public SimpleCardViewHolder(View layout) {
            super(layout);
            tvTitle = (TextView) layout.findViewById(R.id.tv_fruit_item_title);
            tvPrice = (TextView) layout.findViewById(R.id.tv_fruit_item_price);
            tvAdd = (TextView) layout.findViewById(R.id.tv_fruit_item_add);
            ivPic = (ImageView) layout.findViewById(R.id.iv_fruit_item_img);
        }

    }

    /**
     * 添加购物车
     */
    @Background
    void addShopFruitCar(String productID, int isLeiJIa, int isSelected, int num) {
        mApp.getApi().addShopCar(mApp.getUser().getToken(), productID, mShop.getId(), num, isLeiJIa, isSelected, new HttpRequestCallback<AddShopCar>() {
            @Override
            public void onSuccess(int code, String msg, AddShopCar data) {
                refreshUI();
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }


    interface OnItemActionListener {
        void onItemClickListener(View v, int pos);

        void onItemAddClickListener(View v, int pos);
    }
}
